package <#if isCloudModel>${cloudSysEngName}<#else>${packageName}</#if>.utils;
<#if isAuthority>
import <#if isCloudModel>${cloudSysEngName}<#else>${packageName}</#if>.entity.CmSysUserEntity;
<#else>
import <#if isCloudModel>${cloudSysEngName}<#else>${packageName}</#if>.entity.User;
</#if>
import javax.servlet.http.HttpServletRequest;
<#if isRedisSingleLogin>
import java.util.UUID;
</#if>

/**
 * @ClassName SessionUtil
 * @Author zrx
 * @Date 2021/7/20 10:10
 */
public class SessionUtil {

	private static final String SESSION_USER_TOKEN_KEY = "token";

	/**
	 * 登录
	 * @param user
<#if !isRedisSingleLogin>
	 * @param request
</#if>
	 */
<#if isRedisSingleLogin>
    public static void onLogin(<#if isAuthority>CmSysUserEntity<#else>User</#if> user) {
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        user.setToken(token);
        RedisCacheUtil.addAdminByToken(token, user);
	}
<#else>
    public static void onLogin(<#if isAuthority>CmSysUserEntity<#else>User</#if> user, HttpServletRequest request) {
		request.getSession().setAttribute(SESSION_USER_TOKEN_KEY, user);
	}
</#if>

	/**
	 * 退出
	 * @param request
	 */
<#if isRedisSingleLogin>
	public static void logOut(HttpServletRequest request) {
        String token = request.getHeader(SESSION_USER_TOKEN_KEY);
        RedisCacheUtil.del(token);
	}
<#else>
    public static void logOut(HttpServletRequest request) {
		request.getSession().removeAttribute(SESSION_USER_TOKEN_KEY);
		request.getSession().invalidate();
	}
</#if>

	/**
	 * 获取当前用户
	 * @param request
	 * @return
	 */
<#if isRedisSingleLogin>
    public static <#if isAuthority>CmSysUserEntity<#else>User</#if> getUser(HttpServletRequest request) {
		String token = request.getHeader(SESSION_USER_TOKEN_KEY);
    <#if isAuthority>CmSysUserEntity<#else>User</#if> adminByToken = RedisCacheUtil.getAdminByToken(token, <#if isAuthority>CmSysUserEntity<#else>User</#if>.class);
		//重置token过期时长
		if (adminByToken != null) {
			RedisCacheUtil.expire(token, RedisCacheUtil.SESSION_EXPIRE_TIME);
		}
		return adminByToken;
	}
<#else>
    public static <#if isAuthority>CmSysUserEntity<#else>User</#if> getUser(HttpServletRequest request) {
		return (<#if isAuthority>CmSysUserEntity<#else>User</#if>) request.getSession().getAttribute(SESSION_USER_TOKEN_KEY);
	}
</#if>
}

